/** 
 * This module is responsible for asynchronous loading custom YUI-modules,
 * defined by JavaScript developer in the same way as performs loading
 * of YUI native modules. YUI-core is required in the page where this
 * module should work.
 */

// Replacement of YUI() function for using with custom modules
var JAL = function() {
	var J = this;

	J.args = arguments;
	if (!J.args) {
		J.args = {};
	}
	
	J.use = function() {
		if (arguments.length > 1) {
			var callback = arguments[arguments.length - 1];
			
			// Contains names of custom modules
			var customModules = [];
			
			// Names of yui-modules
			var yuiModules = [];
			
			// Sorting module by type (custom, yui)
			for (var i = 0; i < arguments.length - 1; i++) {
				// Adding description of custom module
				if (YUI.jsacc.loader.modules[arguments[i]]) {
					customModules.push(arguments[i]);
				}
				yuiModules.push(arguments[i]);
			}
			
			// Contains modules descriptions in the style of YUI
			J.args.modules = {};

			for (var i = 0; i < customModules.length; i++) {
				J.args.modules[customModules[i]] = {
					fullpath: YUI.jsacc.loader.modules[customModules[i]].fullpath,
					requires: YUI.jsacc.loader.modules[customModules[i]].requires
				};
			}
			
			var preY = YUI(J.args);

			yuiModules.push(function(preY) {
				callback(preY);
			});
			
			preY.use.apply(preY, yuiModules);
//			YUI(J.args).use(yuiModules, );
		}
	};
	
	return J;
};

YUI.namespace('jsacc');
YUI.namespace('jsacc.loader');


/** Contains modules description. */
YUI.jsacc.loader.modules = null;

YUI().use('node-base', 'io-base', 'json-parse', function(Y) {
	var cfg = {
		method: "GET",
		timeout: 5000,
		on: {
			success: function(id, o) {
//				alert(o.responseText);
				YUI.jsacc.loader.modules = Y.JSON.parse(o.responseText);
				Y.Get.script(YUI.jsacc.loader.modules.main.fullpath, {
					onSuccess: function() {
//						alert("main loaded");
					
					},
					onFailure: function() {
						alert("Error loading main module.");
					}
				});
				
				// Loading modules with eager: true
				for (var m in YUI.jsacc.loader.modules) {
					if (YUI.jsacc.loader.modules[m].eager) {
						Y.Get.script(YUI.jsacc.loader.modules[m].fullpath, {
							onSuccess: function() {
//								alert("main loaded");
							
							},
							onFailure: function() {
								alert("Error loading eager module: " + m);
							}
						});
					}
				}
			},
			failure: function(id, o) {
				alert("Loading of modules description failed.");
			}
		}
	};
		
	var url = Y.one("#jsaccDeps").get('value');
	var trnId = Y.io(url, cfg);
});
